Registry.updatePageUrlByDepth   A
last analyzed

Complexity

Conditions 3

Size

Total Lines 15
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 3

Importance

Changes 0
Metric Value
cc 3
eloc 13
dl 0
loc 15
ccs 8
cts 8
cp 1
crap 3
rs 9.75
c 0
b 0
f 0
1
import ListenerAdapter from '@enbock/state-value-observer/ListenerAdapter';
2
import {Observer} from '@enbock/state-value-observer/ValueObserver';
3
import {PageData} from './Router';
4
5
export interface PageDictionary<Type> {
6
  [index: string]: Type
7
}
8
9
export default class Registry {
10
  dictionary: PageDictionary<PageData>;
11
  observer: Observer<PageData | null>;
12
13
  constructor(observer: Observer<PageData | null>) {
14 4
    this.observer = observer;
15 4
    this.dictionary = {};
16
  }
17
18
  attachAdapter(adapter: ListenerAdapter<PageData | null>): void {
19 2
    adapter.addListener(this.updatePageData.bind(this));
20
  }
21
22
  getPages(): PageData[] {
23 2
    const pages: PageData[] = [];
24
25 2
    Object.keys(this.dictionary).forEach((pageName: string) => {
26 2
      const page: PageData = this.dictionary[pageName];
27 2
      pages.push(page);
28
    });
29
30 2
    return pages;
31
  }
32
33
  registerPage(page: PageData) {
34 6
    if (this.observer.value != null) {
35 5
      this.updatePageUrlByDepth(this.observer.value, page);
36
    }
37 6
    this.dictionary[page.name] = page;
38
  }
39
40
  protected updatePageData(newValue: PageData | null): void {
41 3
    if (newValue == null) return;
42 2
    Object.keys(this.dictionary).forEach(
43
      (pageName: string) => {
44 6
        this.updatePageUrlByDepth(newValue, this.dictionary[pageName]);
45
      }
46
    );
47
  }
48
49
  protected updatePageUrlByDepth(currentPage:PageData, registeredPage: PageData): void {
50 11
    let relativeBack: string = '', index: number = 0, newUrl: string;
51
52 11
    if (registeredPage == currentPage) {
53 4
      newUrl = registeredPage.baseUrl.replace(/.*\//, './');
54
    } else {
55 7
      const depth: number = currentPage.baseUrl.replace(/[^\/]*/g, '').length - 1;
56 7
      for (index = 0; index < depth; index++) {
57 13
        relativeBack += '../';
58
      }
59 7
      newUrl = (relativeBack + registeredPage.baseUrl).replace('.././', '../');
60
    }
61
62 11
    registeredPage.currentUrl = newUrl;
63
  }
64
}
65